<template>
  <div class="question-manage">

    <!-- 展示题目 区 -->
    <div class="view-question-title">试题展示</div>
      <div class="view-question" v-if="questions.length">
        <!-- 翻页控制 -->
        <div class="pager">
          <el-button @click="prev" :disabled="currentIndex===0">上一题</el-button>
          <span>{{ currentIndex+1 }} / {{ questions.length }}</span>
          <el-button @click="next" :disabled="currentIndex===questions.length-1">下一题</el-button>
        </div>

        <!-- 平滑过渡 -->
        <transition :name="transitionName" mode="out-in">
          <div class="question-content" :key="currentIndex">
            <el-form label-width="100px">
              <el-form-item label="备注">
                <el-input v-model="currentQues.remark" :disabled="!editing" />
              </el-form-item>
              <el-form-item label="题目内容">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="currentQues.content"
                  :disabled="!editing"
                />
              </el-form-item>

              <!-- 填空题 -->
              <template v-if="currentQues.type===0">
                <el-form-item label="答案">
                  <el-input v-model="currentQues.answer" :disabled="!editing" />
                </el-form-item>
              </template>

              <!-- 选择题 -->
              <template v-else-if="currentQues.type===1">
                <el-form-item label="选项 A">
                  <el-input v-model="currentQues.option1" :disabled="!editing" />
                </el-form-item>
                <el-form-item label="选项 B">
                  <el-input v-model="currentQues.option2" :disabled="!editing" />
                </el-form-item>
                <el-form-item label="选项 C">
                  <el-input v-model="currentQues.option3" :disabled="!editing" />
                </el-form-item>
                <el-form-item label="选项 D">
                  <el-input v-model="currentQues.option4" :disabled="!editing" />
                </el-form-item>
                <el-form-item label="正确答案">
                  <el-select v-model="currentQues.answer" :disabled="!editing" placeholder="请选择">
                    <el-option label="A" value="A" />
                    <el-option label="B" value="B" />
                    <el-option label="C" value="C" />
                    <el-option label="D" value="D" />
                  </el-select>
                </el-form-item>
              </template>

              <!-- 判断题 -->
              <template v-else-if="currentQues.type===2">
                <el-form-item label="正确项">
                  <el-radio-group v-model="currentQues.answer" :disabled="!editing">
                    <el-radio label="正确">正确</el-radio>
                    <el-radio label="错误">错误</el-radio>
                  </el-radio-group>
                </el-form-item>
              </template>

              <!-- 解析 -->
              <el-form-item label="解析">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="currentQues.analysis"
                  :disabled="!editing"
                />
              </el-form-item>
              <!-- 参考资料 -->
              <el-form-item label="参考资料">
                <el-input placeholder="请输入参考资料文件名" v-model="currentQues.file" :disabled="!editing" />
              </el-form-item>
            </el-form>

            <!-- 编辑/保存/取消 按钮 -->
            <div class="action">
              <el-button v-if="!editing" type="primary" @click="onEdit">编辑题目</el-button>
              <div v-else>
                <el-button type="success" >存为新题</el-button>
                <el-button type="success" @click="saveEdit">替换原题</el-button>
                <el-button type="warning" @click="cancelEdit">取消</el-button>
              </div>
            </div>
          </div>
        </transition>
      </div>
      
    <div v-else class="no-data">暂无题目，请先添加。</div>

    <!-- 新增：添加试卷选择区域 -->
    <el-collapse v-model="addPanelActive" accordion>
      <el-collapse-item title="从试卷库中为考试添加试卷" name="addPaper" @click="addPaper">
        <div class="add-paper-form" style="padding: 16px; display: flex; align-items: center; gap: 12px;">
          <el-select v-model="selectedPaperId" placeholder="选择试卷编号" style="width:200px">
            <el-option
              v-for="id in paperList"
              :key="id"
              :label="id"
              :value="id"
            />
          </el-select>
          <el-button type="primary" @click="previewPaper">预览</el-button>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 预览试卷悬浮窗 -->
    <el-dialog
      title="试卷预览"
      v-model="previewDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <div style="max-height:60vh; overflow-y:auto; padding:16px;">
        <div v-for="(q, idx) in previewQuestions" :key="q.id" style="margin-bottom:20px;">
          <div><strong>{{ idx + 1 }}.</strong> （分值 {{ q.score }}）</div>
          <div style="margin:8px 0;">{{ q.content }}</div>
          <template v-if="q.type === 1">
            <div>A. {{ q.option1 }}</div>
            <div>B. {{ q.option2 }}</div>
            <div>C. {{ q.option3 }}</div>
            <div>D. {{ q.option4 }}</div>
          </template>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmAddPaper">确认添加</el-button>
      </template>
    </el-dialog>

    <!-- 新增：查询成绩/改卷区域 -->
    <el-collapse v-model="addPanelActive" accordion>
      <el-collapse-item title="查询成绩/改卷" name="gradeQuery">
        <el-button type="success" @click="queryGrades">查询成绩</el-button>
        <el-button type="success" @click="scorePapers">进行改卷</el-button>
        <div v-if="gradesData.length">
          <!-- EChart柱状图展示 -->
          <div ref="echartContainer" style="height: 300px;"></div>

          <!-- 学生信息列表 -->
          <el-dialog
            title="学生信息"
            v-model="studentDialogVisible"
            width="50%"
            :close-on-click-modal="false"
          >
            <el-table :data="studentList" border>
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="score" label="分数" />
              <el-table-column prop="createTime" label="考试时间" />
             <!-- 使用 v-slot 替代 slot-scope -->
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="viewPaper(scope.row.studentId)"
                  >
                    查看试卷
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <template #footer>
              <el-button @click="studentDialogVisible = false">关闭</el-button>
            </template>
          </el-dialog>
        </div>
        <div v-else>
          <p>暂无成绩数据</p>
        </div>
      </el-collapse-item>
    </el-collapse>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import router from '@/router'
import { useCookies } from 'vue3-cookies'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const { cookies } = useCookies()

// 题目列表
const questions = ref([])
// 当前索引
const currentIndex = ref(0)
// 编辑开关
const editing = ref(false)
// 缓存原始题目
const originalQuestion = ref(null)
// 动画方向
const direction = ref('')

// 控制添加面板展开
const addPanelActive = ref([])
// 可选试卷列表
const paperList = ref([])
// 当前选中试卷ID
const selectedPaperId = ref(null)
// 预览弹窗
const previewDialogVisible = ref(false)
const previewQuestions = ref([])

// 加载题目
async function loadQuestions() {
  const raw = cookies.get('selectedExam')
  let paper_id = null
  try { paper_id = raw.paperId } catch {}
  if (!paper_id) return
  const res = await axios.get(`/api/paper/id?id=${paper_id}&pageSize=${1000}`)
  if (res.data?.code===200) questions.value = res.data.data.records || []
}

// 当前题目
const currentQues = computed(() => questions.value[currentIndex.value] || {})

// 翻页
function prev() {
  if (currentIndex.value>0) {
    direction.value = 'prev'
    currentIndex.value--
  }
}
function next() {
  if (currentIndex.value<questions.value.length-1) {
    direction.value = 'next'
    currentIndex.value++
  }
}

// 过渡名称
const transitionName = computed(() => direction.value==='next' ? 'slide-left' : 'slide-right')

// 点击编辑
function onEdit() {
  editing.value = true
  // 深拷贝当前题目
  originalQuestion.value = JSON.parse(JSON.stringify(currentQues.value))
}
// 取消编辑
function cancelEdit() {
  Object.assign(currentQues.value, originalQuestion.value)
  editing.value = false
}
// 保存修改（接口留空）
async function saveEdit() {
  //组装通用字段
  const payload = {
    id:       currentQues.value.id,
    type:     currentQues.value.type,
    content:  currentQues.value.content,
    score:    currentQues.value.score,
    answer:   currentQues.value.answer,
    analysis: currentQues.value.analysis,
    subject:  currentQues.value.subject,
    file:     currentQues.value.file,
    remark:   currentQues.value.remark
  }
  //如果是选择题，补充四个选项字段
  if (currentQues.value.type === 1) {
    payload.option1 = currentQues.value.option1
    payload.option2 = currentQues.value.option2
    payload.option3 = currentQues.value.option3
    payload.option4 = currentQues.value.option4
  }

  try{
    const res = await axios.put('/api/question/update', payload)
    if (res.data?.code === 200) {
      ElMessage.success('保存成功')
      editing.value = false
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (err) {
    console.log('保存题目失败', err)
    ElMessage.error('网络错误，保存失败')
  }
  editing.value = false
}

// 点击“添加题目”按钮
async function addPaper() {
  // 展开面板
  addPanelActive.value = ['addPaper']
  // 请求可用试卷列表
  try {
    const res = await axios.get('/api/paper/list')
    console.log(res)
    if (res.data.code === 200 && Array.isArray(res.data.data)) {
      // 按从大到小排序
      paperList.value = res.data.data.slice().sort((a, b) => b - a)
    }
  } catch (err) {
    console.error('获取试卷列表失败', err)
    ElMessage.error('获取试卷列表失败')
  }
}

// 点击“预览”按钮
async function previewPaper() {
  if (!selectedPaperId.value) {
    ElMessage.warning('请先选择试卷编号')
    return
  }
  try {
    const res = await axios.get(`/api/paper/id?id=${selectedPaperId.value}&pageSize=${1000}`)
    if (res.data.code === 200 && res.data.data.records) {
      previewQuestions.value = res.data.data.records
      previewDialogVisible.value = true
    }
    console.log(res)
  } catch (err) {
    console.error('预览试卷失败', err)
    ElMessage.error('预览试卷失败')
  }
  loadQuestions()
}

// 点击“确认添加”按钮
async function confirmAddPaper() {
  try {
    const courseRaw = cookies.get('selectedExam')
    const courseId = courseRaw ? courseRaw.id : null
    const res = await axios.put('/api/exam/paper', null, {
      params: { id: courseId, paper: selectedPaperId.value }
    })
    if (res.data.code === 200) {
      ElMessage.success(`添加成功，关联试卷编号 ${selectedPaperId.value}`)
      previewDialogVisible.value = false
      // 收起面板
      addPanelActive.value = []
    } else {
      ElMessage.error(res.data.msg || '添加失败')
    }
  } catch (err) {
    console.error('确认添加失败', err)
    ElMessage.error('确认添加失败')
  }
}

// 新增的状态变量
const gradesData = ref([]) // 存储成绩数据
const studentDialogVisible = ref(false) // 控制学生信息弹窗显示
const studentList = ref([]) // 存储选定成绩区间的学生列表
const echartContainer = ref(null)

// 获取考试ID
const raw = cookies.get('selectedExam')
let examId = null
try { examId = raw.id } catch {}

// 查询成绩并展示柱状图
async function queryGrades() {
  if (!examId) return
  // gradesData.value = []

  // 向后端请求成绩数据
  try {
    const res = await axios.get('/api/answer/grade/page', {
      params: { pageSize: 100, pageNum: 1, examId: examId }
    })
    if (res.data.code === 200) {
      gradesData.value = res.data.data.records || []
      if(gradesData.value.length <= 0){
        ElMessage.success('未查询到完成改卷的记录')
        return
      }
      renderEChart()
    } else {
      ElMessage.error(res.data.msg || '获取成绩失败')
    }
  } catch (err) {
    console.log(err)
    ElMessage.error('网络错误，获取成绩失败')
  }
}

// 渲染EChart柱状图
function renderEChart() {
  const scoreRanges = [0, 60, 70, 80, 90, 100]
  const scoreCounts = [0, 0, 0, 0, 0]

  // 按成绩区间分类
  gradesData.value.forEach(record => {
    const score = record.score
    if (score < 60) scoreCounts[0]++
    else if (score < 70) scoreCounts[1]++
    else if (score < 80) scoreCounts[2]++
    else if (score < 90) scoreCounts[3]++
    else scoreCounts[4]++
  })

  const chartData = {
    xAxis: {
      type: 'category',
      data: ['0-60', '60-70', '70-80', '80-90', '90-100']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: scoreCounts,
        type: 'bar'
      }
    ]
  }

  // 初始化EChart并渲染
  if(!echartContainer.value) return
  const chart = echarts.init(echartContainer.value)
  chart.setOption(chartData)
  
  // 点击柱状图条目展示学生列表
  chart.on('click', async (params) => {
    const rangeIndex = params.dataIndex
    const filteredStudents = gradesData.value.filter(record => {
      const score = record.score
      return score >= scoreRanges[rangeIndex] && score < scoreRanges[rangeIndex + 1]
    })

    console.log(filteredStudents)
    // 获取学生详细信息
    studentList.value = []
    for (const student of filteredStudents) {
      const studentInfo = await getStudentInfo(student.studentId)
      studentList.value.push({ ...studentInfo, score: student.score, createTime: student.createTime })
    }

    // 显示学生信息弹窗
    studentDialogVisible.value = true
  })
  
  console.log('step3')
}

// 获取学生详细信息
async function getStudentInfo(studentId) {
  try {
    const res = await axios.get(`/api/customer/user/id`, {
      params: { id: studentId }
    })
    if (res.data.code === 200) {
      const { username, email, avatar } = res.data.data
      return { studentId, name: username, email, avatar }
    }
  } catch (err) {
    console.error('获取学生信息失败', err)
  }
  return {}
}

async function scorePapers(){
  const Raw = cookies.get('selectedExam')
  const paperId = Raw ? Raw.paperId : null
  console.log(paperId)
  const res = await axios.get("/api/answer/grade/paper", {
    params: { paperId: paperId}
  })
  if(res.data?.code == 200){
    ElMessage.success('批改试卷完成')
    // queryGrades()
  }
}

// 查看试卷
function viewPaper(studentId) {
  // 获取试卷 ID
  const paperId = cookies.get('selectedExam')?.paperId;

  if (paperId) {
    // 将 studentId 和 paperId 保存到 cookies 中
    cookies.set('studentId', studentId);
    cookies.set('paperId', paperId);

    // 跳转到查看试卷的页面
    router.push({path:"/teacher/courseManage/examSomeoneScore"});
  } else {
    ElMessage.error('试卷ID不存在');
  }
}


onMounted(async () => {
  loadQuestions()
  // queryGrades()
})
</script>

<style scoped>
.view-question-title {
  width: 100%;
  height: 60px;
  align-content: center;
  justify-content: center;
  background: #eff;
}
.question-manage {
  padding: 20px;
  background: hsla(216, 33%, 97%, 0.6);
}
.el-collapse { margin-bottom: 20px; }
.el-collapse :deep(.el-collapse-item__header) {
  background-color: #eff !important;
  /* 默认 header 是 flex 布局，左右是箭头和标题文字，我们用 justify-content 居中标题 */
  justify-content: center !important;
}
.view-question {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  position: relative;  /* 为了 clip-子元素定位遮罩 */
  overflow: hidden;    /* 隐藏超出区域 */
}
.pager {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}
.slide-left-enter-active,
.slide-right-enter-active {
  transition: all .3s ease;
}
.slide-left-enter-from { transform: translateX(100%); opacity:0 }
.slide-left-enter-to   { transform: translateX(0); opacity:1 }
.slide-right-enter-from{ transform: translateX(-100%); opacity:0 }
.slide-right-enter-to  { transform: translateX(0); opacity:1 }
.slide-left-leave-active,
.slide-right-leave-active {
  transition: all .3s ease
}
.slide-left-leave-from { transform: translateX(0); opacity:1 }
.slide-left-leave-to   { transform: translateX(-100%); opacity:0 }
.slide-right-leave-from{ transform: translateX(0); opacity:1 }
.slide-right-leave-to  { transform: translateX(100%); opacity:0 }
.question-content {
  background: #fafafa;
  padding: 16px;
  border-radius: 4px;
}
.action { text-align: right; margin-top: 12px; }
.no-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}
.add-box{
  background: #eff;
  height: 80px;
  width: 90%;
}
.paper-actions {
  margin-top: 16px;
}

/* EChart容器样式 */
.echart-container {
  width: 100%;
  height: 300px;
}

.el-dialog {
  width: 50%;
}

.el-table {
  width: 100%;
  text-align: center;
}
</style>
